<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    * {
        margin: 0;
        padding: 0;
    }

    .scroll {
        position: relative;
        width: 400px;
        height: 8px;
        background-color: #ccc;
        margin: 100px auto;
    }

    .bar {
        width: 10px;
        height: 22px;
        background-color: red;
        position: absolute;
        top: -7px;
        left: 0;
        cursor: pointer;
    }

    .mask {
        width: 0;
        height: 100%;
        background-color: red;
        /*position: absolute;
				top: 0;
				left: 0;*/
    }
    .demo{
        text-align: center;
    }
</style>

<body>
    <div class="scroll">
        <div class="bar"></div>
        <div class="mask"></div>
    </div>
    <div class="demo"></div>

</body>

</html>
<script>
	// 获取元素
	var scrollBar = document.querySelector('.scroll');
	var bar = scrollBar.children[0];
	var mask = scrollBar.children[1];
	var demo = document.querySelector(".demo");
	// 拖动原理
	bar.onmousedown = function(event){
		 event = event || window.event;
		var leftVal = event.clientX - this.offsetLeft;
		// 拖动放到down的里面
		var that = this;
		document.onmousemove = function(event){
			 event = event || window.event;
             that.style.left = event.clientX - leftVal + "px";
			// 限制条件
			var val = parseInt(that.style.left);
			if(val < 0){
				that.style.left = 0;
			}else if(val > scrollBar.offsetWight - bar.offsetWight){
				val = scrollBar.offsetWight - bar.offsetWight
			}
			// 移动的距离为遮罩的宽度
			mask.style.width = that.style.left;
			// 显示百分比
			demo.innerHTML = "移动了："+ parseInt(parseInt(that.style.left) / 390 * 100) + "%";
            demo.style.color='red'
            
			// 清除拖动 --- 防止鼠标已经弹起时还在拖动
			window.getSelection ? window.getSelection().removeAllRanges():document.selection.empty();
		}
		// 鼠标抬起停止拖动
		document.onmouseup = function(){
            //清空鼠标移动
			document.onmousemove = null;
		}
	}
</script>